from rest_framework.generics import ListAPIView, CreateAPIView, RetrieveAPIView
from meiduo_admin.serializers.userSerializer import UserSerializer
from rest_framework.views import Response

from users.models import User
from meiduo_admin.utils import PaginatorShow
from meiduo_admin.permissions import *


# class UserManageView(APIView):
#
#     def get(self,request):
#         data = request.query_params
#         bs = UserSerializer(data=data)
#         bs.is_valid(raise_exception=True)
#         data_dict = bs.validated_data
#
#         return Response({
#             "count":data_dict["count"],
#             "lists":data_dict["page_list"],
#             "page":data_dict["page"],
#             "pages":data_dict["pages"],
#             "pagesize":data_dict["pagesize"]
#         })
#
#
#
class UserView(ListAPIView):
    queryset = User.objects.filter(is_staff=True)
    serializer_class = UserSerializer
    permission_classes = [IsAdminUser]

    pagination_class = PaginatorShow

    def get_queryset(self):

        keyword = self.request.query_params.get("keyword")
        if keyword:
            return self.queryset.filter(username__contains=keyword)
        else:
            return self.queryset.all()

    def get(self,request, *args, **kwargs):
        datas = self.list(request, *args, **kwargs)
        for user in datas.data["lists"]:
            user["mobile"] = user["phone_number"]
        return datas

    def post(self,request):
        data = request.data
        data["phone_number"] = data.pop("mobile")

        bs = UserSerializer(data=data)
        bs.is_valid(raise_exception=True)
        bs.save()

        bs.validated_data["mobile"] = bs.validated_data.pop("phone_number")

        return Response({
            "id":bs.data["id"],
            "username": bs.data["username"],
            "mobile":bs.validated_data["mobile"],
            "email":bs.data["email"]
        },status=201)


